#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
AI营销方案生成系统 - 响应辅助工具
功能：提供统一的API响应格式化工具
作者：AI营销系统开发团队
创建时间：2024
"""

from flask import jsonify, g
from typing import Any, Dict, Optional
import uuid
from datetime import datetime, timezone


def success_response(
    data: Optional[Dict[str, Any]] = None,
    message: str = '操作成功',
    status_code: int = 200
) -> tuple:
    """
    生成成功响应
    
    Args:
        data: 响应数据
        message: 响应消息
        status_code: HTTP状态码
        
    Returns:
        tuple: (响应JSON, 状态码)
    """
    response_data = {
        'success': True,
        'message': message,
        'code': status_code,
        'timestamp': datetime.now(timezone.utc).isoformat(),
        'request_id': getattr(g, 'request_id', str(uuid.uuid4()))
    }
    
    if data is not None:
        response_data['data'] = data
    
    return jsonify(response_data), status_code


def error_response(
    message: str = '操作失败',
    error: Optional[str] = None,
    error_code: Optional[str] = None,
    status_code: int = 500,
    data: Optional[Dict[str, Any]] = None
) -> tuple:
    """
    生成错误响应
    
    Args:
        message: 错误消息
        error: 详细错误信息
        error_code: 错误代码
        status_code: HTTP状态码
        data: 额外数据
        
    Returns:
        tuple: (响应JSON, 状态码)
    """
    response_data = {
        'success': False,
        'message': message,
        'code': status_code,
        'timestamp': datetime.now(timezone.utc).isoformat(),
        'request_id': getattr(g, 'request_id', str(uuid.uuid4()))
    }
    
    if error:
        response_data['error'] = error
    
    if error_code:
        response_data['error_code'] = error_code
    
    if data is not None:
        response_data['data'] = data
    
    return jsonify(response_data), status_code


def paginated_response(
    data: list,
    page: int,
    per_page: int,
    total: int,
    message: str = '获取数据成功'
) -> tuple:
    """
    生成分页响应
    
    Args:
        data: 分页数据
        page: 当前页码
        per_page: 每页数量
        total: 总数量
        message: 响应消息
        
    Returns:
        tuple: (响应JSON, 状态码)
    """
    total_pages = (total + per_page - 1) // per_page
    
    pagination_info = {
        'page': page,
        'per_page': per_page,
        'total': total,
        'total_pages': total_pages,
        'has_prev': page > 1,
        'has_next': page < total_pages
    }
    
    return success_response(
        data={
            'items': data,
            'pagination': pagination_info
        },
        message=message
    )


def validation_error_response(
    errors: Dict[str, str],
    message: str = '数据验证失败'
) -> tuple:
    """
    生成验证错误响应
    
    Args:
        errors: 验证错误字典
        message: 错误消息
        
    Returns:
        tuple: (响应JSON, 状态码)
    """
    return error_response(
        message=message,
        error_code='VALIDATION_ERROR',
        status_code=400,
        data={'validation_errors': errors}
    )


def not_found_response(
    resource: str = '资源',
    message: Optional[str] = None
) -> tuple:
    """
    生成404响应
    
    Args:
        resource: 资源名称
        message: 自定义消息
        
    Returns:
        tuple: (响应JSON, 状态码)
    """
    if message is None:
        message = f'{resource}不存在'
    
    return error_response(
        message=message,
        error_code='NOT_FOUND',
        status_code=404
    )


def unauthorized_response(
    message: str = '未授权访问'
) -> tuple:
    """
    生成401响应
    
    Args:
        message: 错误消息
        
    Returns:
        tuple: (响应JSON, 状态码)
    """
    return error_response(
        message=message,
        error_code='UNAUTHORIZED',
        status_code=401
    )


def forbidden_response(
    message: str = '禁止访问'
) -> tuple:
    """
    生成403响应
    
    Args:
        message: 错误消息
        
    Returns:
        tuple: (响应JSON, 状态码)
    """
    return error_response(
        message=message,
        error_code='FORBIDDEN',
        status_code=403
    )


def rate_limit_response(
    message: str = '请求频率超限'
) -> tuple:
    """
    生成429响应
    
    Args:
        message: 错误消息
        
    Returns:
        tuple: (响应JSON, 状态码)
    """
    return error_response(
        message=message,
        error_code='RATE_LIMIT_EXCEEDED',
        status_code=429
    )